package jmine.tec.web.servlet.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import jmine.tec.web.servlet.util.WebSpringHelper;

import org.springframework.beans.factory.BeanFactory;

import bancosys.tec.persist.authorization.AuthorizationManager;
import bancosys.tec.persist.authorization.AuthorizationStatus;

/**
 * @author takeshi
 */
public class NoAuthorizationFilter implements Filter {

    private AuthorizationManager authorizationManager;

    private volatile FilterConfig filterConfig;

    /**
     * {@inheritDoc}
     * 
     * @see javax.servlet.Filter#destroy()
     */
    public void destroy() {
    }

    /**
     * {@inheritDoc}
     * 
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (this.authorizationManager == null) {
            BeanFactory beanFactory = WebSpringHelper.getBeanFactory(this.filterConfig.getServletContext());
            this.authorizationManager = (AuthorizationManager) beanFactory.getBean("boAuthorizationManager", AuthorizationManager.class);
        }
        AuthorizationStatus oldStatus = this.authorizationManager.getThreadAuthorizationStatus();
        this.authorizationManager.setThreadAuthorizationStatus(AuthorizationStatus.DISABLED);
        try {
            chain.doFilter(request, response);
        } finally {
            this.authorizationManager.setThreadAuthorizationStatus(oldStatus);
        }
    }

    /**
     * {@inheritDoc}
     * 
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    public void init(FilterConfig arg0) throws ServletException {
        this.filterConfig = arg0;
    }

    /**
     * @param authorizationManager the authorizationManager to set
     */
    public void setAuthorizationManager(AuthorizationManager authorizationManager) {
        this.authorizationManager = authorizationManager;
    }
}
